import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_member/routes/application.dart';
import 'package:flutter_member/widget/custom_appbar.dart';
import 'package:flutter_member/widget/loading_dialog.dart';
import 'package:flutter_member/widget/no_data.dart';
import 'package:flutter_member/widget/universal_card.dart';
import 'package:flutter_member/widget/universal_card_item.dart';
import 'package:parse_server_sdk/parse_server_sdk.dart';

/// 订阅服务
class SubscriptionServicePage extends StatefulWidget {
  @override
  _SubscriptionServicePageState createState() => _SubscriptionServicePageState();
}

class _SubscriptionServicePageState extends State<SubscriptionServicePage> {

  var logoState;
  var studentId;

//  我的订阅
  List<dynamic> _mySubscriptionList = [];

//  全部可订阅的服务
  List<dynamic> _allService = [];

//  加載中
  bool _loading = true;

  @override
  void initState() {
    _getStudentSubscription();
    // _getAllTuitionService();
    super.initState();
  }

  /// 获得已订阅服务
  Future<void> _getStudentSubscription() async {
    final ParseUser user = await ParseUser.currentUser();
    var queryMember = QueryBuilder<ParseObject>(ParseObject("Member"));
    queryMember.whereEqualTo("objectId", user.get("member")["objectId"]);
    var repMem = await queryMember.query();
    if (repMem.results != null && repMem.success) {
      if (repMem.results.first['student'] != null ||
          repMem.results.first['students'] != null) {
        var query =
        QueryBuilder<ParseObject>(ParseObject("StudentSubscription"));
        query.whereEqualTo('student', repMem.results.first['student']);
        query.includeObject(["service.category", "student.branch"]);
        var repSub = await query.query();
        if (repSub.results != null && repSub.success) {
          setState(() {
            _loading = false;
            _mySubscriptionList = repSub.results.map((e) => e).toList();
          });
        } else {
          setState(() => _loading = false);
        }
        _mySubscriptionList.map((e) => print(e)).toList();
      }
    }
  }

  //下拉刷新
  Future<Null> _refresh() async {
    setState(() {});

    return;
  }
  @override
  Widget build(BuildContext context) {
    final width = MediaQuery.of(context).size.width;
    return CustomAppBar(
      title: '已訂閱的服務',
      hight: 84,
      childRight: IconButton(
        color: Colors.white,
        icon: Icon(Icons.add),
        onPressed: () =>
            Application.jump(context, "/page/personal/add_service"),
      ),
      body: EasyRefresh(
        onRefresh: _refresh,
        child: _body(),
      ),
    );
  }

  Widget _body() {
    if (_loading) {
      return CLoadingDialog(
        text: '加载中',
      );
    } else {
      return SingleChildScrollView(
        child: _mySubscriptionList.length != 0
            ? Column(
          children: _listSubscription(),
        )
            : Center(
          child: NoDataWidget(),
        ),
      );
    }
  }

  List<Widget> _listSubscription() {
    return _mySubscriptionList
        .map((data) => UniversalCard(
      title: data['title'],
      // url: data['cateUrl'],
      children: [
        UniversalCardItem(
            icon: 'images/locations.png',
            title: data['student']['branch']['address']),
        UniversalCardItem(
            icon: 'images/price.png', title: data['price'].toString()),
        UniversalCardItem(
            icon: 'images/index_service.png',
            title: formatDate(
                data['createdAt'], [yyyy, '-', mm, '-', dd])),
      ],
    ))
        .toList();
  }
}
